package com.cloud.code.牛客网;

import java.util.*;

public class Test18 {

    public static void main(String[] args) {
        String input = "1,2-4,7-10,6";
        int num = 9;

        Map<Integer, String> map = new TreeMap<>();

        String[] split = input.split(",");
        Arrays.stream(split).forEach(temp -> {
            if (temp.contains("-")) {
                String[] split1 = temp.split("-");
                map.put(Integer.valueOf(split1[0]), split1[1]);
            } else {
                map.put(Integer.valueOf(temp), null);
            }
        });

        System.out.println(map);
        List<Integer> list = new ArrayList<>();
        map.keySet().forEach(integer -> {
            list.add(integer);
        });

        for (int i = 0; i < list.size() - 2; i++) {
            if (list.get(i) == num) {
                break;
            }

            if (list.get(0) > num) {
                break;
            }

            if (list.get(i + 1) == num) {
                break;
            }

            if (list.get(i) < num && list.get(i + 1) > num) {
                String s = map.get(list.get(i));
                if (s == null) {
                    break;
                } else {
                    if (num < Integer.valueOf(map.get(list.get(i)))) {
                        String s1 = map.get(list.get(i));
                        map.put(list.get(i), num + "");
                        map.put(num, s1);
                        break;
                    } else {
                        break;
                    }
                }
            }
        }

        if (num > list.get(list.size() - 1)) {
            if (null == map.get(list.get(list.size() - 1)) || num > Integer.valueOf(map.get(list.get(list.size() - 1)))) {

            } else {
                String max = map.get(list.get(list.size() - 1));
                map.put(list.get(list.size() - 1), num + "");
                map.put(num + 1, max);
            }
        }

        Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, String> next = iterator.next();
            if (next.getValue() == null) {
                if (iterator.hasNext()) {
                    System.out.print(next.getKey() + ",");
                } else {
                    System.out.print(next.getKey());
                }
            } else {
                if (iterator.hasNext()) {
                    System.out.print(next.getKey() + "-" + next.getValue() + ",");
                } else {
                    System.out.print(next.getKey() + "-" + next.getValue());
                }
            }
        }
    }
}
